package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

// CORS 中间件处理跨域资源共享
func CORS() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 记录请求信息
		fmt.Printf("Request Method: %s, Origin: %s\n", c.Request.Method, c.Request.Header.Get("Origin"))

		// 动态获取并验证请求源
		origin := c.Request.Header.Get("Origin")
		
		// 允许本地开发环境的请求源
		if origin != "" && (strings.HasPrefix(origin, "http://localhost:") || strings.HasPrefix(origin, "http://127.0.0.1:")) {
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		} else if origin == "http://121.36.228.151:8081" {
			// 生产环境域名
			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
		}
		
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With, X-User-ID, X-User-Name, X-Token")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, HEAD, PATCH, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			fmt.Println("Handling OPTIONS request")
			c.AbortWithStatus(http.StatusNoContent)
			return
		}

		c.Next()
	}
}
